#!/bin/bash

#vobsub2pgm -c 255,0,255,255 -i toto.ifo -g 2  toto french ; pgm2txt french ; srttool -s -w < french.srtx > french.srt
# toto.ifo toto.idx toto.sub file must exist

FFMPEG="ffmpeg"

syntaxe="

Usage :

./$(basename $0)
-i Image file or DVD directory
-o BUILDDIR
-p FFMpeg program

bash $(basename $0) -i <INPUTFILE> -o <BUILD DIR> -p <FFMPEG program> -b <video bitrate>

Example for windows:
bash $(basename $0) -i E:/ -o c:/build/ -p ffmpeg.exe -b 1200k 2>&1 | tee c:/build/log.log
bash $(basename $0) -i E:/ -o c:/build/ -p ffmpeg.exe -s 700M 2>&1 |  tee c:/build/log.log

Example for Unix:
cd \"/Volumes/iMovie/DivX/Films Enfants/Nanny.McPhee.And.The.Big.Bang\"
bash $(basename $0) -i \"ISO DVD/aymo_peterpan.iso\" -o \"DVDRIP\" -p ffmpeg -b 2500k 2>&1 | tee \"DVDRIP/aymo_peterpan.log\"

"

while getopts ":o:i:p:b:s:h:" OPTION

do
case $OPTION in
h)
echo $syntaxe
exit 1
;;
o)
BUILDDIR=$OPTARG
;;
p)
FFMPEG=$OPTARG
;;
b)
VIDEOBITRATE=$OPTARG
;;
s)
SIZE=$OPTARG
;;
i)
ISO=$OPTARG
;;
:)
echo "*OUTPUTFILE** OPTION \"$OPTARG\" sans arg"
exit 1
;;
\?)
echo "*** option $OPTARG inconnue !!!"
exit 1
;;
esac
done


killMplayerProcess()
{
echo
echo "Killing mplayer process ..."
for pid in `ps auwx | grep mplayer   | grep -v grep | awk '{print $2}'`; do kill -9 $pid; done
sleep 2
for pid in `ps auwx | grep mplayer   | grep -v grep | awk '{print $2}'`; do kill -9 $pid; done
sleep 2
echo
}

shellout(){
echo "$1"
echo
echo "Existing with error !!!"
exit 1
}


[ "$ISO" = "" ] &&  shellout "$syntaxe"

[ "$BUILDDIR" = "" ] &&  shellout "$syntaxe"

[ "$SIZE" = "" ] && SIZE=700M
ALLLOG="${BUILDDIR}/dvd-all.txt"
echo "ISO = $ISO"
echo "Create dir ${BUILDDIR}"
mkdir -p "${BUILDDIR}/"


if [ ! -f  "${ALLLOG}" ]
then
echo "Scanning DVD ... >> ${ALLLOG}"
echo "mplayer -identify -v -vo null -ao null dvd://1 -dvd-device \"$ISO\" > ${ALLLOG} 2>&1 &"
mplayer -identify -v -vo null dvd://1 -dvd-device "$ISO" > "${ALLLOG}"  2>&1 &
sleep 5
else
echo "File ${ALLLOG} already exist, nothing to do"
fi

killMplayerProcess

NUMBER_OF_TITLE=`cat "${ALLLOG}" | grep "There are " | grep " titles on this DVD." | sed -e "s/There are //g" | sed -e "s/ titles on this DVD.//g"`
DVD_TITLE=`cat "${ALLLOG}" | grep "ID_DVD_VOLUME_ID=" | sed -e "s/ID_DVD_VOLUME_ID=//g"`

if [ "$DVD_TITLE" = "" ]
then
    DVD_TITLE=`basename $ISO .iso`
fi

BUILDDIR="${BUILDDIR}/$DVD_TITLE"
mkdir -p "${BUILDDIR}"
mv "$ALLLOG" "${BUILDDIR}"
ALLLOG="${BUILDDIR}/dvd-all.txt"

echo "Number of title in this DVD ${ALLLOG} : $NUMBER_OF_TITLE"

echo
echo
echo "Trying to retrieve ifo File from DVD"

if [ -f "$ISO" ]
then
DVD_DIR=`hdiutil attach "$ISO" | perl -e "while (<>) {print \"/Volumes$'\" if (/\/Volumes/);}"`
else
DVD_DIR="$ISO"
fi

find "$DVD_DIR" -iname "*.ifo" | while read line
do
cp "$line" "${BUILDDIR}/"
done
if [ -f "$ISO" ]
then
hdiutil detach "$DVD_DIR"
fi

echo
echo


title=1
while [ $title -le $NUMBER_OF_TITLE ]
do
mkdir -p "${BUILDDIR}/${title}"
TITLELOGFILE="${BUILDDIR}/${title}/dvd-$title.txt"
if [ ! -f "$TITLELOGFILE" ]
then
echo "Generating info file $TITLELOGFILE"
mplayer -identify -v -vo null dvd://$title -dvd-device "$ISO" > "$TITLELOGFILE"  2>&1 &
sleep 2
else
echo "File $TITLELOGFILE already exist, nothing to do"
fi
let title=title+1
done


killMplayerProcess

echo
echo
echo








echo "Generating Chapters file"
title=1
while [  $title -le $NUMBER_OF_TITLE ]
do
newtitle=`printf "%02d" ${title}`
chapfile="${BUILDDIR}/${title}/chapters-title-${title}.txt"
if [ ! -f "$chapfile" ]
then
CHAPTERS=`cat "${BUILDDIR}/${title}/dvd-${title}.txt"  | grep "^CHAPTERS: " | sed -e "s/^CHAPTERS://g" |  sed -e "s/,/ /g"`
echo "Creating chapter file for title ${newtitle} ${chapfile}"
COUNT=0
for x in `echo "${CHAPTERS}"`
do
let COUNT=${COUNT}+1
NEWCOUNT=`printf "%02d" $COUNT`
echo "CHAPTER${NEWCOUNT}=${x}"  >> "$chapfile"
echo "CHAPTER${NEWCOUNT}NAME=Chapter ${NEWCOUNT}"  >> "$chapfile"
done
else
echo "File $chapfile already exist nothing to do"
fi
let title=title+1
done

echo
echo
echo

echo "Dumping stream from DVD"
title=1
while [  $title -le $NUMBER_OF_TITLE ]
do
mkdir -p "${BUILDDIR}/${title}"
titledumpstream="${BUILDDIR}/${title}/${DVD_TITLE}_${title}.vob"
titlelog="${BUILDDIR}/${title}/${DVD_TITLE}_${title}.log"

echo "Dump stream title $title in file $titledumpstream - see $titlelog for log"
rm -f  "$titlelog"
echo "Command : mplayer -dumpstream dvd://${title}  -dvd-device \"$ISO\" -dumpfile \"$titledumpstream\" >> \"$titlelog\"  2>&1 "
[ ! -f "$titledumpstream" ] && mplayer -dumpstream dvd://${title}  -dvd-device "$ISO" -dumpfile "$titledumpstream" >> "$titlelog"  2>&1
let title=title+1
done

killMplayerProcess

echo
echo
echo

title=1
while [  $title -le $NUMBER_OF_TITLE ]
do
mkdir -p "${BUILDDIR}/${title}"
titledumpstream="${BUILDDIR}/${title}/${DVD_TITLE}_${title}.vob"
titlelog="${BUILDDIR}/${title}/dvd-${title}.txt"
if [ -f "$titlelog" ]
then
for sid in `cat "$titlelog" | grep "subtitle ( sid )" | sed -e "s/subtitle ( sid ): //g" | sed -e "s/ language://g" | sed -e "s/ /=/g"`
do
realsid=`echo "$sid" | sed -e "s/=.*$//g"`
lang=`echo "$sid" | sed -e "s/^.*=//g"`
SUBFILE="${BUILDDIR}/${title}/${DVD_TITLE}_${title}-sid-${realsid}-lang-${lang}"
if [ ! -f "${SUBFILE}.idx" ]
then
echo "Extracting subtitle sid : $sid"
echo "Command : mencoder \"${titledumpstream}\" -vobsubout \"${SUBFILE}\" -vobsuboutindex 0 -sid \"$realsid\" -o null -nosound -ovc frameno"
mencoder "${titledumpstream}" -vobsubout "${SUBFILE}" -vobsuboutindex 0 -sid "$realsid" -o null -nosound -ovc frameno
rm -f null
else
echo "File ${SUBFILE}.idx already exist, skip this process"
fi
done
else
echo "File $titlelog already exist, nothing to do"
fi
let title=title+1
done



echo
echo
echo

#get audio information
#mplayer -identify -aid 128 -vo null -ao null -frames 0 ${DVD_TITLE}_1.vob
#mplayer -identify -aid 160 -vo null -ao pcm -aofile toto.wav -frames 0 ${DVD_TITLE}_2.vob
#mplayer  ${DVD_TITLE}_2.vob  -aid 160  -ao pcm:waveheader:file=toto.wav -ni -vo null BUG


title=1
while [  $title -le $NUMBER_OF_TITLE ]
do
mkdir -p "${BUILDDIR}/${title}"
titledumpstream="${BUILDDIR}/${title}/${DVD_TITLE}_${title}.vob"

for aid in `cat "${BUILDDIR}/${title}/dvd-${title}.txt"  | grep "audio stream" | grep "aid" | sed -e "s/.*aid: //g" | sed -e "s/\.$//g"`
do
LANG=`cat "${BUILDDIR}/$title/dvd-$title.txt" | grep audio | grep language | grep "aid: $aid"  | sed -e "s/.*language: //g" | sed -e "s/ aid.*$//g"`
FORMAT=`cat "${BUILDDIR}/$title/dvd-$title.txt" | grep "audio stream" | grep "$aid" | grep format | sed -e "s/.*format: //g" | sed -e "s/ .*$//g"`

echo

AUDIOFILE="${BUILDDIR}/${title}/${DVD_TITLE}_${title}-aid-${aid}-lang-$LANG.$FORMAT"
VOBFILE="${BUILDDIR}/${title}/${DVD_TITLE}_${title}.vob"
if [ ! -f "$AUDIOFILE" ]
then
date
echo "Extraction/Dumping Audio $AUDIOFILE"
mplayer "${VOBFILE}" -aid ${aid}  -dumpaudio -dumpfile "$AUDIOFILE"  2> null
#"${FFMPEG}" -y -i "${AUDIOFILE}" -vn -sn -acodec dca -ab 320k -ac 6 -strict -2 "${AUDIOFILE}.aac-5.1-320k.beta.dts"
"${FFMPEG}" -y -i "${AUDIOFILE}" -vn -sn -acodec libfaac -ab 320k -ar 48000 -ac 6   "${AUDIOFILE}-5.1-320k.aac"
"${FFMPEG}" -y -i "${AUDIOFILE}" -vn -sn -f ac3 -acodec ac3 -ab 320k -ar 48000 -ac 6   "${AUDIOFILE}-5.1-320k.ac3"
"${FFMPEG}" -y -i "${AUDIOFILE}" -vn -sn -acodec libmp3lame -ab 320k -f mp3   "${AUDIOFILE}-5.1-320k.mp3"


rm -f null
else
echo "File $AUDIOFILE already exist, nothing to do"
fi
done
let title=title+1
done

echo
echo
echo



title=1
while [ $title -le $NUMBER_OF_TITLE ]
do

VOBFILE="${BUILDDIR}/${title}/${DVD_TITLE}_${title}.vob"
DURATION=`cat "${BUILDDIR}/${title}/dvd-$title.txt" | grep "ID_DVD_TITLE_${title}_LENGTH=" | sed -e "s/ID_DVD_TITLE_${title}_LENGTH=//g" | sed -e "s/\.[0-9]*//g"`
S=`echo ${SIZE} | sed -e "s/[aA-zZ]*//g"`
NEWBITRATE=$((8 * $S * 1000 / $DURATION))
echo "B=$B"
echo "DURATION=$DURATION"
echo "S=$S"
echo "NEWBITRATE=$NEWBITRATE"

[ "$VIDEOBITRATE" = "" ] && [ "$SIZE" = "" ] &&  VIDEOBITRATE=1200k
[ "$VIDEOBITRATE" = "" ] &&  VIDEOBITRATE="${NEWBITRATE}k"
VARIABLEBITRATE=`echo $VIDEOBITRATE | sed -e 's/k//g'`
VARIABLEBITRATE=$(($VARIABLEBITRATE * 110 / 100))
VARIABLEBITRATE="${VARIABLEBITRATE}k"

MP4FILE="${BUILDDIR}/${title}/${DVD_TITLE}_${title}-${VIDEOBITRATE}-hq-x264.mp4"

echo "** $DURATION for ${MP4FILE} **"
echo "** $SIZE for ${MP4FILE} **"
echo "Command : \"$FFMPEG\"  -y -i \"${VOBFILE}\"  -pass 1  -passlogfile \"${VOBFILE}.log\"  -threads 0 -vcodec libx264 -deinterlace -b ${VIDEOBITRATE} -bt ${VARIABLEBITRATE} -flags +loop -refs 5 -subq 6 -me_range 21 -b_strategy 1 -level 30 -g 300 -keyint_min 30 -sc_threshold 40 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.7 -qmax 51 -qdiff 4 -i_qfactor 0.71428572 -maxrate 5000k -bufsize 2M -cmp 1 -s 720x480 -an -f mp4  \"${BUILDDIR}/${title}/null-pass1.mp4\" "
[ ! -f "${MP4FILE}" ] && "$FFMPEG"  -y -i "${VOBFILE}"  -pass 1  -passlogfile "${VOBFILE}.log"  -threads 0 -vcodec libx264 -deinterlace -b ${VIDEOBITRATE} -bt ${VARIABLEBITRATE} -flags +loop -refs 5 -subq 6 -me_range 21 -b_strategy 1 -level 30 -g 300 -keyint_min 30 -sc_threshold 40 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.7 -qmax 51 -qdiff 4 -i_qfactor 0.71428572 -maxrate 5000k -bufsize 2M -cmp 1 -s 720x480 -an -f mp4  "${BUILDDIR}/${title}/null-pass1.mp4"
rm -f "${BUILDDIR}/${title}/null-pass1.mp4"
echo "Command : \"$FFMPEG\"  -y -i \"${VOBFILE}\"  -pass 2  -passlogfile \"${VOBFILE}.log\"  -threads 0 -vcodec libx264 -deinterlace -b ${VIDEOBITRATE} -bt ${VARIABLEBITRATE} -flags +loop -refs 5 -subq 6 -me_range 21 -b_strategy 1 -level 30 -g 300 -keyint_min 30 -sc_threshold 40 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.7 -qmax 51 -qdiff 4 -i_qfactor 0.71428572 -maxrate 5000k -bufsize 2M -cmp 1 -s 720x480 -an -f mp4  \"${MP4FILE}\" "
[ ! -f "${MP4FILE}" ] && "$FFMPEG"  -y -i "${VOBFILE}"  -pass 2  -passlogfile "${VOBFILE}.log"  -threads 0 -vcodec libx264 -deinterlace -b ${VIDEOBITRATE} -bt ${VARIABLEBITRATE} -flags +loop -refs 5 -subq 6 -me_range 21 -b_strategy 1 -level 30 -g 300 -keyint_min 30 -sc_threshold 40 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.7 -qmax 51 -qdiff 4 -i_qfactor 0.71428572 -maxrate 5000k -bufsize 2M -cmp 1 -s 720x480 -an -f mp4  "${MP4FILE}"
let title=title+1
done


echo
echo
exit 0
echo
echo



"mkvmerge" -o "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip.mkv"  "--language" "1:ara" "--forced-track"
"1:no" "-d" "1" "-A" "-S" "-T" "--no-global-tags" "--no-chapters"
"D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\${DVD_TITLE}_1-740k-hq-x264.mp4"
"--language" "0:ara" "--forced-track" "0:no" "-a" "0" "-D" "-S" "-T" "--no-global-tags"
"--no-chapters" "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\${DVD_TITLE}_1-aid-128-lang-ar.ac3"
"--language" "0:fre" "--forced-track" "0:no" "-s" "0" "-D" "-A" "-T" "--no-global-tags" "--no-chapters"
"D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\${DVD_TITLE}_1-sid-0-lang-fr.idx" "--language" "0:fre"
"--track-name" "0:SRT sous-titre (FR)" "--default-track" "0:yes" "--forced-track" "0:no" "-s" "0" "-D" "-A" "-T"
"--no-global-tags" "--no-chapters" "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\FRENCH SUBTITLE.srt" "--language"
"0:eng" "--track-name" "0:SRT subtitle (EN)" "--forced-track" "0:no" "-s" "0" "-D" "-A" "-T" "--no-global-tags"
"--no-chapters" "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\ENGLISH SUBTITLE.srt" "--track-order"
"0:1,1:0,2:0,3:0,4:0" "--attachment-mime-type" "text/plain" "--attachment-name" "FRENCH SUBTITLE.srt"
"--attach-file" "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\FRENCH SUBTITLE.srt" "--attachment-mime-type"
"text/plain" "--attachment-name" "ENGLISH SUBTITLE.srt" "--attach-file"
"D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\ENGLISH SUBTITLE.srt" "--attachment-mime-type"
"image/jpeg" "--attachment-name" "jacquette.jpg" "--attach-file" "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\jacquette.jpg"
"--chapter-language" "ara" "--chapters" "D:\\DVD-Mplayer\\Le_Messager_ar_fre_dvdrip\\1\\chapters-title-1.txt"